package com.suian.spring.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class LockTest {
    @Autowired
    private RedisDistributedLock redisLock;
    String lockKey = "order_create";
    String requestId = UUID.randomUUID().toString();
    String requestId2 = UUID.randomUUID().toString();

    @Autowired
    private RedissonClient redissonClient;

    public void Lock1() {

        try {
            //尝试获取锁
            if (redisLock.tryLock(lockKey, requestId)) {
                //执行业务

                System.out.println("T1执行成功");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            } else {
                System.out.println("T1 系统繁忙，请稍等");
            }
        } finally {
            //释放锁
            redisLock.releaseLock(lockKey, requestId);
        }
    }

    public void Lock2() {
        try {
            //尝试获取锁
            if (redisLock.tryLock(lockKey, requestId2)) {
                //执行业务

                System.out.println("T2执行成功");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                System.out.println("T2 系统繁忙，请稍等");
            }
        } finally {
            //释放锁
            redisLock.releaseLock(lockKey, requestId2);
        }

    }

    public void lockRedission() throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        // 尝试获取锁，最多等待 10 秒，锁的过期时间为 20 秒
        boolean isLock = lock.tryLock(2, 20, TimeUnit.SECONDS);
        if (isLock) {
            try {
                System.out.println("Redission 1 锁住了");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                lock.unlock();
            }
        }else {
            System.out.println("T1 系统繁忙，请稍等");
        }
    }

    public void lockRedission2() throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        boolean isLock = lock.tryLock(2, 20, TimeUnit.SECONDS);
        if (isLock) {
            try {
                System.out.println("Redission 2 锁住了");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                lock.unlock();
            }
        }else {
            System.out.println("T2 系统繁忙，请稍等");
        }
    }

}
